package com.zqweb.gulimall.essearch.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadTest3 {
    public static ExecutorService threadPool = Executors.newFixedThreadPool(15);
    public static void main(String[] args) {
        CompletableFuture<Object> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("开始执行任务1...");
            int res = 10 / 2;
            System.out.println("结束执行任务1...");
            return res;
        },threadPool);
        CompletableFuture<Object> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("开始执行任务2...");
            // 睡上2秒，模拟超时效果
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String res = "future2";
            System.out.println("结束执行任务2...");
            return res;
        },threadPool);
        /*future1.runAfterEitherAsync(future2,() -> {
            System.out.println("开始执行任务3...");
        },threadPool);*/
        /*future1.acceptEitherAsync(future2,(res) -> {
            System.out.printf("接收到前2个任务某1个任务的执行结果为：%s\n",res);
            System.out.println("开始执行任务3...");
        },threadPool);*/
        CompletableFuture<String> future3 = future1.applyToEitherAsync(future2, (res) -> {
            System.out.printf("接收到前2个任务某1个任务的执行结果为：%s", res);
            System.out.println("开始执行任务3...");
            return "任务3对应的返回结果：努力！";
        }, threadPool);

        /*future1.runAfterBothAsync(future2,() -> {
            System.out.println("开始执行任务3...");
        },threadPool);*/
        /*future1.thenAcceptBothAsync(future2,(res1,res2) -> {
            System.out.printf("接收到前2个任务的执行结果分别为：%s 和 %s\n",res1,res2);// 5  future2
            System.out.println("开始执行任务3...");
        },threadPool);*/
        /*CompletableFuture<String> future3 = future1.thenCombineAsync(future2, (res1, res2) -> {
            System.out.printf("接收到前2个任务的执行结果分别为：%s 和 %s\n", res1, res2);// 5  future2
            System.out.println("开始执行任务3...");
            return res1 + res2 + "，我是任务3的返回结果：Combine！";
        }, threadPool);*/
        String res = "";
        try {
            res = future3.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.printf("future3对应业务任务的执行结果为：%s\n",res);

        // 关闭当前线程的资源调用
        threadPool.shutdown();

    }

}
